package pers.xiaoliang.concurrency.example.concurrent;

import lombok.extern.slf4j.Slf4j;
import pers.xiaoliang.concurrency.annotation.ThreadSafe;

import java.util.List;
import java.util.concurrent.*;

/**
 * @version v1.0
 * @description: 并发容器CopyOnWriteArrayList
 * @author: xiaoliang.liu
 * @date: 2018/7/28 21:02
 */
@Slf4j
@ThreadSafe
public class CopyOnWriteArrayListExample1 {

    /**
     * 线程数量(模拟并发数)
     */
    private static int threadTotal = 200;
    /**
     * 请求次数
     */
    private static int clientTotal = 5000;

    private static List<Integer> list = new CopyOnWriteArrayList<>();

    public static void main(String[] args) throws InterruptedException {
        // 获得线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 信号量
        final Semaphore semaphore = new Semaphore(threadTotal);

        // 闭锁
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);

        for (int i = 0; i < clientTotal; i++) {
            int finalI = i;
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    update(finalI);
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println(e);
                }

                // 闭锁计数器减一
                countDownLatch.countDown();
            });
        }

        // 阻塞
        countDownLatch.await();

        // 关闭线程池
        executorService.shutdown();
        System.out.println(list.size());
        executorService.shutdown();
    }

    private static void update(int i) {
        list.add(i);
    }
}
